import storage from 'store'
import expirePlugin from 'store/plugins/expire'
import { login, getInfo, logout } from '@/api/login'
import { ACCESS_TOKEN } from '@/store/mutation-types'
import { welcome } from '@/utils/util'
import { TUILogin } from '@tencentcloud/tui-core'
import { framework } from '@/TUIKit/adapter-vue'
import { genTestUserSig } from '@/TUIKit'
// import { genTestUserSig } from '@/TUIKit'
storage.addPlugin(expirePlugin)
const user = {
  state: {
    token: '',
    name: '',
    welcome: '',
    avatar: '',
    roles: [],
    info: {}
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
    },
    SET_NAME: (state, { name, welcome }) => {
      state.name = name
      state.welcome = welcome
    },
    SET_AVATAR: (state, avatar) => {
      state.avatar = avatar
    },
    SET_ROLES: (state, roles) => {
      state.roles = roles
    },
    SET_INFO: (state, info) => {
      state.info = info
    }
  },

  actions: {
    // 登录
    Login({ commit, state }, userInfo) {
      return new Promise((resolve, reject) => {
        console.log('登录信息', userInfo)
        const userSig = genTestUserSig({
          SDKAppID: 1600084628,
          secretKey: 'be7e8cc168feb00b6c562b4ef8c46ccfea630bd3325d8cad87e351ddd778a165',
          userID: userInfo.username
        })
        TUILogin.login({
          SDKAppID: 1600084628,
          userID: userInfo.username,
          userSig: userSig.userSig,
          useUploadPlugin: true,
          framework
        })
          .then((res) => {
            console.log('登录成功', res.data.errorInfo === 'success')
            if (res.data.errorInfo === 'success') {
              storage.set('isReady', true)
            }
          })
          .catch((error) => {
            console.log('登录失败', error)
            // reject(error)
          })

        login(userInfo)
          .then((response) => {
            console.log('返回的数据', response)
            const result = response.result
            // const result = response.data
            // console.log('数据', state.checklogin)
            // commit('SET_LOGIN', true)
            console.log('登录成功', result)
            if (result && result.code !== 500) {
              storage.set(ACCESS_TOKEN, result.token, new Date().getTime() + 7 * 24 * 60 * 60 * 1000)
              commit('SET_TOKEN', result.token)

              resolve(result)
            } else {
              // 如果 result 为 null 或 code 为 500，抛出错误
              throw new Error(response.message || '登录失败')
            }
          })
          .catch((error) => {
            // console.log('错误捕获', error)

            reject(error)
          })
      })
    },

    // 获取用户信息
    GetInfo({ commit }) {
      return new Promise((resolve, reject) => {
        // 请求后端获取用户信息 /api/user/info
        getInfo()
          .then((response) => {
            const { result } = response
            if (result) {
              // const role = { ...result.role }
              // role.permissions = result.role.permissions.map((permission) => {
              //   const per = {
              //     ...permission,
              //     actionList: (permission.actionEntitySet || {}).map((item) => item.action)
              //   }
              //   return per
              // })
              // role.permissionList = role.permissions.map((permission) => {
              //   return permission.permissionId
              // })
              // 覆盖响应体的 role, 供下游使用
              // result.role = role

              // commit('SET_ROLES', role)
              // console.log('用户信息', result)

              commit('SET_INFO', result)
              commit('SET_NAME', { name: result.username, welcome: welcome() })
              commit('SET_AVATAR', result.avatar)
              // 下游
              resolve(result)
            } else {
              reject(new Error('getInfo: roles must be a non-null array !'))
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },

    // 登出
    Logout({ commit, state }) {
      return new Promise((resolve) => {
        // logout(state.token)
        // storage.remove(ACCESS_TOKEN)
        logout()
          .then(() => {
            commit('SET_TOKEN', '')
            commit('SET_INFO', {})
            // commit('SET_ROLES', [])
            // TUILogin.logout()
            // const userID = TUILogin.getLoginUser()
            // if (storage.get('isReady')) {
            //   TUILogin.logout()
            // } else {
            //   storage.set('isReady', false)
            // }

            // if (userID) {
            //   TUILogin.logout()
            // }
            storage.remove(ACCESS_TOKEN)
            resolve()
          })
          .catch((err) => {
            console.log('logout fail:', err)
            // resolve()
          })
          .finally(() => {})
      })
    }
  }
}

export default user
